package com.toolbox.controller;

import com.toolbox.service.ToolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/api/tools/document")
public class DocumentController {

    @Autowired
    private ToolService toolService;

    /**
     * 文档转换接口
     * @param file 上传的文件
     * @param targetFormat 目标格式
     * @return 转换后的文件
     */
    @PostMapping("/convert")
    public ResponseEntity<byte[]> convertDocument(
            @RequestParam("file") MultipartFile file,
            @RequestParam("targetFormat") String targetFormat) {
        
        try {
            // 参数验证
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body("文件不能为空".getBytes());
            }
            
            if (targetFormat == null || targetFormat.isEmpty()) {
                return ResponseEntity.badRequest().body("目标格式不能为空".getBytes());
            }
            
            // 调用服务层进行转换
            byte[] convertedData = toolService.convertDocument(file, targetFormat);
            
            // 生成响应头
            HttpHeaders headers = new HttpHeaders();
            String originalFileName = file.getOriginalFilename();
            String fileNameWithoutExt = originalFileName != null ? 
                    originalFileName.substring(0, originalFileName.lastIndexOf('.')) : "converted";
            String newFileName = fileNameWithoutExt + "." + targetFormat;
            
            // 设置响应头 - 处理中文文件名编码问题
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            try {
                // 按照RFC 5987标准编码中文文件名
                String encodedFileName = java.net.URLEncoder.encode(newFileName, "UTF-8")
                        .replace("+", "%");
                headers.add("Content-Disposition", 
                        "attachment; filename*=UTF-8''" + encodedFileName);
            } catch (Exception e) {
                // 编码失败时使用默认文件名
                headers.setContentDispositionFormData("attachment", "converted_file." + targetFormat);
            }
            headers.setContentLength(convertedData.length);
            
            return new ResponseEntity<>(convertedData, headers, HttpStatus.OK);
            
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage().getBytes());
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件处理失败".getBytes());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("转换失败".getBytes());
        }
    }
}